<template>
  <common-page title="告警详情">
    <div class="warnstatus">
      <div class="statusBox">
        <div>状态:</div>
        <span @click="handleWatchFlow"
          >{{ statusDic.find((item) => item.value == form.status) && statusDic.find((item) => item.value == form.status).label }}><span></span
        ></span>
      </div>

      <div class="cardBox">
        <div class="statusCard" v-if="form.warningTimeoutFlag == 1">确警超时</div>
        <div class="statusCard" v-if="form.handleTimeoutFlag == 1">处理超时</div>
      </div>
    </div>
    <section-card title="基本信息">
      <avue-form ref="form" v-model="form" :option="formOption">
        <template #type>
          <div v-if="form.type">
            {{ form.type ? handleTypeName(form.type) : '--' }}
          </div>
          <div v-else>--</div>
        </template>
        <!-- <template #level>
          <div v-if="form.level">
            {{
              handleValue(false, form.level, [
                {
                  lable: '一级告警',
                  value: '1'
                },
                {
                  lable: '二级告警',
                  value: '2'
                },
                {
                  lable: '三级告警',
                  value: '3'
                }
              ])
            }}
          </div>
          <div v-else>--</div>
        </template> -->

        <!-- <template #pushWay>
          <div v-if="form.pushWay">
            {{
              handleValue(false, form.pushWay, [
                { lable: '移动网络', value: '1' },
                { lable: '卫星', value: '2' }
              ])
            }}
          </div>
          <div v-else>--</div>
        </template> -->

        <template #shipName>
          <div v-if="form.shipName">
            {{ form.shipName }}
          </div>
          <div v-else>--</div>
        </template>
        <template #videoPointsType>
          <div v-if="form.videoPointsType">
            {{ form.videoPointsType ? handleValue(false, form.videoPointsType) : '--' }}
          </div>
          <div v-else>--</div>
        </template>
        <template #tenantName>
          <div v-if="form.tenantName">
            {{ form.tenantName }}
          </div>
          <div v-else>--</div>
        </template>
      </avue-form>
    </section-card>

    <section-card title="告警信息">
      <avue-crud
        v-if="list && list.length > 0"
        ref="crud"
        v-model="crudForm"
        class="crud-table"
        :option="tableOption"
        :data="list"
        :table-loading="loading"
        :header-cell-class-name="() => 'crud-table-head'"
        :cell-class-name="() => 'crud-cell'"
        @hook:mounted="$ele.tableMount($refs.crud)"
        @hook:beforeDestroy="$ele.tableDestroy($refs.crud)"
      >
        <template slot="fileAddress" slot-scope="{ row }">
          <!-- <el-image
            v-if="row.fileAddress"
            class="file-img"
            ref="fileImg"
            :src="downLoadUrl(row.fileAddress)"
            :preview-src-list="[downLoadUrl(row.fileAddress)]"
          >
          </el-image> -->
          <div class="warn-img">
            <UpImg v-if="row.fileAddress" :list="[row.fileAddress]" :limit="1" :disabled="true"></UpImg>
            <div v-else>--</div>
            <div v-show="row.fileSecret" style="color: red">Md5：{{ row.fileSecret }}</div>
          </div>
        </template>
      </avue-crud>
      <div style="margin-top: 20px" v-if="isSysAutoWarn">{{ form && form.reason ? form.reason : '--' }}</div>
    </section-card>

    <section-card title="视频回放" v-if="form.videoAddress">
      <video
        :src="videoUrl(form.videoAddress)"
        controls="controls"
        style="width: 500px"
        x5-video-player-fullscreen="true"
        x5-playsinline
        playsinline
        webkit-playsinline
        controlsList="nodownload"
      >
        您的浏览器不支持 video 标签。
      </video>
      <div v-show="form.videoSecret" style="color: red">Md5:{{ form.videoSecret }}</div>
      <!-- <div style="margin-top: 10px" v-if="form.videoAddress">
        poster="@/assets/images/video-bg.png"
        <el-button 
          type="primary"
          @click="downloadMp4(videoUrl(form.videoAddress))"
          >下载视频</el-button
        >
      </div> -->
    </section-card>
    <template #extra>
      <div>
        <el-button type="normal" @click="back">返回</el-button>
      </div>
    </template>

    <WarnStatus ref="WarnStaus" />
  </common-page>
</template>

<script>
import { formOption, tableOption } from './detail.option'
import { getDetail, changeStatus, handleWarnings, getPageByWarningId, getWarnModuleList } from '@/api/warnmessage'
import WarnStatus from './warnstatus.vue'
import { genFormOptionWithFields, isSysAutoWarnModule } from '@/utils/util'
import { getDict } from '@/api/dict'
export default {
  components: {
    WarnStatus
  },
  data() {
    return {
      name: 'warnMessageDetail',
      id: '',
      form: {
        remarks: ''
      },
      crudForm: {},
      disabled: true,
      taskName: '',
      list: [],
      nodeList: [],
      handle: {},
      loading: false,
      isShow: false,
      title: '告警处理',
      imageUrl: '',
      fileAddress: '',
      statusDic: [
        // {
        //   label: '待确警',
        //   value: 0
        // },
        {
          label: '待处理',
          value: 1
        },
        {
          label: '待处理',
          value: 2
        },
        // {
        //   label: '误警',
        //   value: 4
        // },
        {
          label: '已处理',
          value: 5
        }
      ],
      warnModuleArr: [],
      installation: []
    }
  },
  computed: {
    formOption() {
      return genFormOptionWithFields(formOption.call(this))
    },
    tableOption() {
      return genFormOptionWithFields(tableOption.call(this))
    },

    downLoadUrl(url) {
      console.log('🤡 ~ url:', url)
      return function (url) {
        return url && `/api/oss/download/sturgeon?objectName=${encodeURIComponent(url)}`
      }
    },
    videoUrl() {
      return function (url) {
        let u = navigator.userAgent
        let isiOS = !!u.match(/\(i[^;]+;( U;)? CPU.+Mac OS X/) //ios终端
        let isSafari = /Safari/.test(u) && !/Chrome/.test(u) //Safari
        if (isiOS || isSafari) {
          return `/api/oss/downloadVideoBySafari?bucketName=sturgeon&objectName=${encodeURIComponent(url)}`
        } else {
          return `/api/oss/download/sturgeon?objectName=${encodeURIComponent(url)}`
        }
      }
    },
    isSysAutoWarn() {
      return isSysAutoWarnModule(this.form?.type)
    }
  },
  created() {
    this.id = this.$route.query.id
    this.initDist()
  },
  mounted() {},
  methods: {
    downloadMp4(fileUrl) {
      // let fileUrl =
      //   "https://gltzg.ixunhang.com/api/im/attachment/preview?objectName=%2Fwarn%2FFREMO007%2F007ef15474b343309d693f5c7cf5da5c.mp4";

      fetch(fileUrl)
        .then((res) => res.blob())
        .then((blob) => {
          const a = document.createElement('a')
          const url = window.URL.createObjectURL(blob)
          a.href = url
          fileUrl = decodeURIComponent(fileUrl)
          a.download = fileUrl.slice(fileUrl.lastIndexOf('/') + 1)
          a.click()
          window.URL.revokeObjectURL(url)
        })
    },
    handleValue(dic, item, defaultDic) {
      const res = this.installation
      return (res.find((i) => i.value == item) && res.find((i) => i.value == item).lable) || item || '--'
    },
    initDist() {
      // this.$store.dispatch('dict/getDictAll', [
      //   // 'warning_model',
      //   'installation_point'
      // ])
      // this.getWarnModule()

      Promise.all([getDict('installation_point'), getWarnModuleList()]).then((res) => {
        this.installation = res[0].result
        this.warnModuleArr = res[1].result
        this.initForm()
        console.log('🤡 ~ res:', this.installation)
      })
    },
    getWarnModule() {
      getWarnModuleList().then((res) => {
        this.warnModuleArr = res.result
      })
    },
    handleTypeName(value) {
      let name = ''
      const obj = this.warnModuleArr.find((i) => i.warningModelCode == value)
      if (obj != undefined) {
        name = obj.warningModelName
      }
      return name
    },
    // 处理
    onClickWarnings() {
      handleWarnings({
        warningId: this.form.id,
        fileAddress: this.fileAddress.join(','),
        remarks: this.form.remarks,
        status: this.form.status == 2 ? 3 : 2
      }).then((res) => {
        console.log('resss', res)
        this.$message.success('操作成功')
        this.close()
        this.back()
      })
    },
    // 确警误警
    onClickStatusBtn(status) {
      changeStatus({
        id: this.form.id,
        status
      }).then((res) => {
        this.$message.success('操作成功')
        this.back()
      })
    },
    initForm() {
      getDetail({ id: this.id }).then((res) => {
        this.form = res.result || {}
        this.list = this.form && this.form.warningAttachmentVoList
      })
      getPageByWarningId({ warningId: this.id }).then((res) => {
        console.log('getPageByWarningId', res)
        this.nodeList = res.result.records
      })
    },
    close() {
      this.isShow = false
    },
    handleWatchFlow() {
      this.$refs.WarnStaus.show(this.nodeList)
    },

    back() {
      this.$router.push('/warning/list')
    }
  }
}
</script>

<style scoped lang="scss">
.warnstatus {
  position: relative;
  font-size: 18px;
  color: #333;
  padding-left: 18px;
  display: flex;
  align-items: center;
  font-weight: bold;
  justify-content: space-between;
  .statusBox {
    display: flex;
    span {
      margin-left: 10px;
      color: var(--theme);
      cursor: pointer;
    }
  }
  .cardBox {
    display: flex;
    .statusCard {
      font-size: 12px;
      background: rgba(255, 8, 0, 1);
      border-radius: 4px;
      margin-right: 10px;
      color: #fff;
      font-weight: 500;
      padding: 4px 6px;
    }
  }
}

.card-title {
  margin-top: 20px;
  margin-bottom: 20px;
}

.btn-section {
  padding: 20px 0;
}
::v-deep .el-icon-error {
  display: none !important;
}
.warn-img {
  ::v-deep .el-upload-list__item {
    width: 300px;
    height: 160px;
    margin: 0 auto;
  }
}
</style>
